import { Controller } from "../Controller.js";
import { post, get, del } from "../server/Http.js"

/** @private */
class AnnotationInspector extends Controller {

    constructor(parent, cfg = {}) {

        super(parent);
        console.log("AnnotationInspector", cfg)
        this._projectId = cfg.projectId;
        if (!cfg.propertiesTabElement) {
            throw "Missing config: propertiesTabElement";
        }

        if (!cfg.propertiesElement) {
            throw "Missing config: propertiesElement";
        }

        this._metaObject = null;

        this._propertiesTabElement = cfg.propertiesTabElement;
        this._propertiesElement = cfg.propertiesElement;
        this._propertiesTabButtonElement = this._propertiesTabElement.querySelector(".xeokit-tab-btn");

        if (!this._propertiesTabButtonElement) {
            throw "Missing DOM element: ,xeokit-tab-btn";
        }

        this._onModelUnloaded = this.viewer.scene.on("modelUnloaded", (modelId) => {
            if (this._metaObject) {
                const metaModels = this._metaObject.metaModels;
                for (let i = 0, len = metaModels.length; i < len; i++) {
                    if (metaModels[i].id === modelId) {
                        this.clear();
                        return;
                    }
                }
            }
        });

        this.bimViewer.on("reset", () => {
            this.clear();
        });

        // document.addEventListener('click', this._clickListener = (e) => {
        //     if (!e.target.matches('.xeokit-accordion .xeokit-accordion-button')) {
        //         return;
        //     } else {
        //         if (!e.target.parentElement.classList.contains('active')) {
        //             e.target.parentElement.classList.add('active');
        //         } else {
        //             e.target.parentElement.classList.remove('active');
        //         }
        //     }
        // });

        this.clear();
    }
    showObjectPropertySets(objectId) {
        this._setAnnotationSets();
    }

    clear() {
        const html = [],
            localizedText = this.viewer.localeService.translate('propertiesInspector.noObjectSelectedWarning') || 'No object inspected. Right-click or long-tab an object and select \'Inspect Properties\' to view its properties here.';
        html.push(`<div class="element-attributes">`);
        html.push(`<p class="xeokit-i18n subsubtitle no-object-selected-warning" data-xeokit-i18n="propertiesInspector.noObjectSelectedWarning">${localizedText}</p>`);
        html.push(`</div>`);
        const htmlStr = html.join("");
        this._propertiesElement.innerHTML = htmlStr;
    }

    _setAnnotationSets() {
        const html = [];
        html.push(`
        <table class="annotation-table" id="markerTable">
                <thead>
                    <tr>
                        <th>编号</th>
                        <th>类别</th>
                        <th>内容</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 动态插入数据 -->
                </tbody>
            </table>`);

        get("/mark/list", { projectUuid: this._projectId }).then((res) => {
            if (res.code === 0) {
                this.bimViewer._annotationsTool.createAnnotations(res.data);
                this.renderTable(res.data)
            }
        }).catch();

        this.renderTable = (markers) => {

            const tableBody = document.querySelector("#markerTable tbody");
            tableBody.innerHTML = ""; // 清空表格内容
            for (let index = 0; index < markers.length; index++) {
                const marker = markers[index];
                const row = document.createElement("tr");
                row.innerHTML = `
                    <td  class="annotation-number" id="${marker.uuid}" >${marker.number}</td>
                    <td class="annotation-content">
                        <select id="${marker.uuid}">
                            <option value="一般" ${marker.title == '一般' ? 'selected' : ''}>一般</option>
                            <option value="重要" ${marker.title == '重要' ? 'selected' : ''}>重要</option>
                        </select>
                    </td>
                    <td class="annotation-content" contenteditable="true"  id="${marker.uuid}">${marker.content}</td>
                    <td class="annotation-span-delete">
                        <span   id="${marker.uuid}" >删除</span>
                    </td>`
                    ;
                tableBody.appendChild(row);
            }
            tableBody.querySelectorAll(".annotation-content").forEach((element) => {
                //失去焦点
                element.addEventListener("blur", (event) => {
                    var elm = this.getMarker(event.target.id, markers)
                    elm.content = event.target.innerText;
                    this.bimViewer._annotationsTool.remove(event.target.id);
                    this.bimViewer._annotationsTool.createAnnotation(elm);
                    this.renderTable(markers)
                    post("/mark/update", elm)
                })
                element.addEventListener("focus", (event) => {
                    console.log("focus", event.target.id)
                })
                element.addEventListener("change", (event) => {
                    var elm = this.getMarker(event.target.id, markers)

                    elm.title = event.target.value;
                    this.bimViewer._annotationsTool.remove(event.target.id);
                    this.bimViewer._annotationsTool.createAnnotation(elm);
                    this.renderTable(markers)
                    post("/mark/update", elm)
                    // 这里可以添加 Ajax 代码，提交选择的值到后端
                });
            })
            tableBody.querySelectorAll(".annotation-number").forEach((element) => {
                element.addEventListener("click", (event) => {
                    console.log("click", event.target.id)
                    this.bimViewer._annotationsTool.flyTo(event.target.id);
                })
            })
            tableBody.querySelectorAll(".annotation-span-delete").forEach((element) => {
                element.addEventListener("click", (event) => {
                    // 弹出确认框
                    const isConfirmed = window.confirm("确定要删除这个标记吗？");

                    if (isConfirmed) {
                        // 确认删除，执行删除操作
                        del("/mark/delete", event.target.id).then((res) => {
                            if (res.code === 0) {
                                markers = markers.filter(marker => marker.uuid !== event.target.id);
                                this.bimViewer._annotationsTool.remove(event.target.id);
                                this.renderTable(markers)
                            }
                        });
                    } else {
                        // 如果用户取消删除，可以执行一些额外操作（可选）
                        console.log("删除操作已取消");
                    }
                })
            })
        }

        this.getMarker = (uuid, markers) => {
            for (let index = 0; index < markers.length; index++) {
                const element = markers[index];
                if (element.uuid === uuid) {
                    return element;
                }

            }
        }



        this._propertiesElement.innerHTML = html.join("");
        // renderTable();

    }

    setEnabled(enabled) {
        if (!enabled) {
            this._propertiesTabButtonElement.classList.add("disabled");
            this._setAnnotationSets();
        } else {
            this._propertiesTabButtonElement.classList.remove("disabled");
        }
    }
    refreshData() {
        this._setAnnotationSets();
    }
    destroy() {
        super.destroy();
        this.viewer.scene.off(this._onModelLoaded);
        this.viewer.scene.off(this._onModelUnloaded);
        document.removeEventListener('click', this._clickListener);
    }
}

function capitalizeFirstChar(str) {
    if (!str) {
        return str;
    }
    return str.charAt(0).toUpperCase() + str.slice(1);
}

export { AnnotationInspector };